<!DOCTYPE html>
<html>
<head>
    <title>JS数组</title>
    <meta charset="utf-8"/>
    <script src="../../js/jquery-1.10.1.min.js"></script>
    <script>
        //1.forEach函数。n[].forEach(function(value, index, array) {
        var colors = ["red", "green", "blue"];
        colors.forEach(alert);
       // colors.forEach(console.log);

        //2.map函数 [].map(function(value, index, array)
        var data = [1, 2, 3, 4];
        var arrayOfSquares = data.map(function (item) {
            return item * item;
        });
        alert(arrayOfSquares);

        //3.filter函数。
        var f = data.filter(function(item){
            return item > 2;
        });
        alert(f);

        //4.some函数。some意指“某些”，指是否“某些项”合乎条件。与下面的every算是好基友，every表示是否“每一项”都要靠谱
        var scores = [5, 8, 3, 10];
        var current = 7;

        function higherThanCurrent(score) {
            return score > current;
        }

        if (scores.some(higherThanCurrent)) {
            alert("朕准了！");
        }

        //5.every 跟some的基友关系已经是公开的秘密了，同样是返回Boolean值，不过，every需要每一个妃子都要让朕满意
        if (scores.every(higherThanCurrent)) {
            console.log("every--朕准了！");
        } else {
            console.log("every--来人，拖出去斩了！");
        }

        //6. indexOf方法在字符串中自古就有，string.indexOf(searchString, position)。数组这里的indexOf方法与之类似
        var data = [2, 5, 7, 3, 5];

        console.log(data.indexOf(5, "x")); // 1 ("x"被忽略)
        console.log(data.indexOf(5, "3")); // 4 (从3号位开始搜索)

        console.log(data.indexOf(4)); // -1 (未找到)
        console.log(data.indexOf("5")); // -1 (未找到，因为5 !== "5")

        //7.lastIndexOf  lastIndexOf方法与indexOf方法类似
        var data = [2, 5, 7, 3, 5];

        console.log(data.lastIndexOf(5)); // 4
        console.log(data.lastIndexOf(5, 3)); // 1 (从后往前，索引值小于3的开始搜索)
        console.log(data.lastIndexOf(4)); // -1 (未找到)

        //8.reduce reduce是JavaScript 1.8中才引入的，中文意思为“减少”、“约简”。
        // 不过，从功能来看，我个人是无法与“减少”这种含义联系起来的，反而更接近于“迭代”、“递归(recursion)”
        var sum = [1, 2, 3, 4].reduce(function (previous, current, index, array) {
            return previous + current;
        });
        console.log("8.reduce:" + sum)

            var matrix = [
                [1, 2],
                [3, 4],
                [5, 6]
            ];
            // 二维数组扁平化
            var flatten = matrix.reduce(function (previous, current) {
                return previous.concat(current);
            });
            console.log("8.reduce:" + flatten);

        //9. reduceRight跟reduce相比,实现上差异在于reduceRight是从数组的末尾开始实现
        var data = [1, 2, 3, 4];
        var specialDiff = data.reduceRight(function (previous, current, index) {
            if (index == 0) {
                return previous + current;
            }
            return previous - current;
        });
        console.log("9.reduceRight:"+ specialDiff);
    </script>

</head>
<body>
    <p>JS数组</p>
</body>
</html>